package com.pdool.game.logic.handler.rank;

import com.pdool.common.constants.MsgId;
import com.pdool.common.msg.common.NullReq;
import com.pdool.common.msg.rank.ScoreRankResp;
import com.pdool.game.core.msg.IHandler;
import com.pdool.game.core.msg.MsgHandler;
import com.pdool.game.logic.mgr.UserMgr;
import com.pdool.game.logic.service.RankService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Set;

@Component
@MsgHandler(MsgId.QUERY_SCORE_RANK)
@Slf4j
public class ScoreRankHandler implements IHandler<NullReq, ScoreRankResp> {
    @Autowired
    RankService rankService;

    @Override
    public ScoreRankResp handle(Long roleId, NullReq nullReq) throws IOException {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = rankService.query100();

        ScoreRankResp.Builder builder = ScoreRankResp.newBuilder();

        int rank = 0;

        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            long rankRoleId = Long.parseLong(typedTuple.getValue());
            int score = typedTuple.getScore().intValue();
            String roleName = UserMgr.getInstance().getRoleNameMap().get(rankRoleId);
            if (roleName == null){
                continue;
            }
            rank++;
            ScoreRankResp.RankItem.Builder builder1 = ScoreRankResp.RankItem.newBuilder();
            builder1.setScore(score);
            builder1.setRank(rank);
            builder1.setRoleId(rankRoleId);
            builder1.setName(roleName);
            builder.addRankList(builder1);
        }
        return builder.build();
    }
}